package com.miplus.ccrm.core.service.conf;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.core.controller.vo.LabelResVo;
import com.miplus.ccrm.core.controller.vo.conf.PostTreeResVo;
import com.miplus.ccrm.core.pojo.SysPost;
import com.miplus.ccrm.core.mapper.SysPostMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author pc
* @description 针对表【sys_post(系统地址表)】的数据库操作Service实现
* @createDate 2024-03-26 12:58:13
*/
@Service
public class SysPostServiceImpl extends ServiceImpl<SysPostMapper, SysPost>
    implements SysPostService{

    @Override
    public List<LabelResVo> getProvinceList()
    {
        return baseMapper.getProvinceList();
    }

    @Override
    public List<LabelResVo> getCityList(String province)
    {
        return baseMapper.getCityList(province);
    }

    @Override
    public List<LabelResVo> getDistrictList(String city)
    {
        return baseMapper.getDistrictList(city);
    }


    @Override
    public List<PostTreeResVo> getPostTree()
    {
        List<SysPost> all=baseMapper.selectList(
                new QueryWrapper<SysPost>()
                        .select("indexs","name","parentid","datalevel")
                        .in("datalevel","2","3","4")
            );
        List<PostTreeResVo> tree = new ArrayList<>();
        List<SysPost> parent = all.stream().filter(p -> JPubUtils.IsEqual(p.getDatalevel(),"2")).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(parent)){
            for(SysPost g : parent) {
                PostTreeResVo resVo=new PostTreeResVo();
                resVo.setId(g.getIndexs());
                resVo.setName(g.getName());
                tree.add(resVo);
                addChildren(resVo, all);
            }
        }
        return tree;
    }

    private void addChildren(PostTreeResVo resVo, List<SysPost> all) {
        List<SysPost> tempList = all.stream()
                .filter(p -> resVo.getId().equals(p.getParentid()))
                .collect(Collectors.toList());
        List<PostTreeResVo> resVoList=new ArrayList<>();
        for(SysPost g: tempList){
            PostTreeResVo r=new PostTreeResVo();
            r.setId(g.getIndexs());
            r.setName(g.getName());
            resVoList.add(r);

            addChildren(r, all);
        }
        resVo.setChildren(resVoList);
    }
}




